<template>
  <view class="content">
    <view class="navigation" ref="navigationRef">
      <eui-navbar ref="EuiNavBar" title="蓝牙打印机列表" rightIcon="none" color="#000000" backgroundColor="#FFFFFF" />
    </view>
    <view class="footer">
      <scroll-view
          :refresher-triggered="triggered"
          @refresherrefresh="templateUpper"
          :refresher-enabled='true'
          scroll-y="true"
      >
        <view class="uni-list">
          <radio-group @change="radioChange">
            <label class="uni-list-cell uni-list-cell-pd" v-for="(item, index) in devices" :key="index">
              <view>
                <radio :value="index"/>
              </view>
              <view class="flex_1">
                <view>{{ item.name }}</view>
                <view class="flex_2">{{ item.deviceId }}</view>
              </view>
            </label>
          </radio-group>
        </view>
      </scroll-view>
    </view>
    <view class="menu-footer">
        <eui-button type="base2" @buttonClick="cancel" title="取消" />
        <eui-button type="primary" @buttonClick="determine" title="确定" />
    </view>
  </view>
</template>


<script setup lang="ts">
import {onBeforeUnmount, onBeforeMount, ref} from 'vue';
import {onLoad} from '@dcloudio/uni-app';

const type = ref('');
const current = ref('');
const c_height = ref(0);
const devices = ref([
  // {
  //   "name": "Printer_5722_BLE",
  //   "deviceId": "AB8DB9BB-DDC5-15DD-7D8A-0DF183FE1FF0",
  //   "services": [
  //     "000018F0-0000-1000-8000-00805F9B34FB",
  //     "E7810A71-73AE-499D-8C15-FAA9AEF0C3F2"
  //   ]
  // },
  // {
  //   "name": "NPcAZzWUdJ74X1phfMFQenyXs",
  //   "deviceId": "78EC86E1-7931-D1FB-1FAF-E0A13E74478C"
  // }
]);
const triggered = ref(false);


//  MARK: - 页面生命周期: 页面加载
onLoad( (option) => {
  openBluetoothAdapterAndCheckState();
  if (option) {
    type.value = option.type;
  }
});

onBeforeUnmount(() => {
  // 组件销毁时确保停止BLE扫描
  stopBLEScan();
});


// 初始化蓝牙模块 获取本机蓝牙适配器状态
const openBluetoothAdapterAndCheckState = () => {
  uni.openBluetoothAdapter({
    success: () => {
      console.log('成功打开蓝牙适配器');
      // 蓝牙适配器已经成功打开，接下来检查蓝牙状态
      checkBluetoothState();
    },
    fail: err => {
      uni.showToast({
        duration: 2000,
        icon: 'none',
        title: '打开蓝牙适配器失败，请打开蓝牙!'
      });
      console.error('打开蓝牙适配器失败：', err);
    }
  });
};

// 获取蓝牙适配器状态
const checkBluetoothState = () => {
  uni.getBluetoothAdapterState({
    success: res => {
      console.log(JSON.stringify(res));
      if (res.available) {
        if (res.discovering) {
          stopBLEScan();
        }
        startBLEScan();
      } else {
        uni.showToast({
          duration: 2500,
          icon: 'none',
          title: '蓝牙不可用或未启用。'
        });
      }
    },
    fail: err => {
      uni.showToast({
        duration: 2500,
        icon: 'none',
        title: '获取蓝牙适配器状态失败：' + JSON.stringify(err)
      });
      console.error('获取蓝牙适配器状态失败：', err);
    }
  });
};

// 开始扫描BLE设备
const startBLEScan = () => {
  uni.startBluetoothDevicesDiscovery({
    services: [], // 您可以指定感兴趣的服务UUID
    success: () => {
      console.log('开始扫描BLE设备。');
    },
    fail: err => {
      console.error('启动BLE扫描失败：', err);
      // 自动刷新
      triggered.value = false;
      templateUpper()
    }
  });

  // 监听已发现的设备
  uni.onBluetoothDeviceFound(res => {
   // console.log('发现设备：', res.devices);
    const name = res.devices[0].name;
    if (name !== '') {
      const deviceId = res.devices[0].deviceId;
      const advertisServiceUUIDs = res.devices[0].advertisServiceUUIDs;
      let old = '';
      const oldDevices = devices.value.filter(item=>item['deviceId'] === deviceId)
      if (devices.value.length > 0 && oldDevices.length > 0) {
        // old = devices.value[devices.value.length - 1].deviceId;
        old = oldDevices[0].deviceId
      }
      if (old !== deviceId) {
        devices.value.push({
          name: name,
          deviceId: deviceId,
          services: advertisServiceUUIDs
        });
      }
      // console.log(183, '______________---', devices.value);
    }
    // 在这里处理已发现的设备，更新列表等。
  });
};

// 停止扫描BLE设备
const stopBLEScan = () => {
  uni.stopBluetoothDevicesDiscovery({
    success: () => {
      console.log('停止扫描BLE设备。');
    },
    fail: err => {
      console.error('停止BLE扫描失败：', err);
    }
  });
  // 关闭蓝牙模块。并释放系统资源
  uni.closeBluetoothAdapter({
    success(res) {
      console.log(res)
    }
  })
};

// 点击单选框
const radioChange = (evt) => {
  current.value = evt.detail.value;
};

// 确定返回
const determine = () => {
  if (current.value === '' && current.value !== 0) {
    uni.showToast({
      duration: 3500,
      icon: 'none',
      title: '请先选择打印机！'
    });
    return false;
  }
  AddMyMenuByUser(devices.value[current.value]);
};

// 取消
const cancel = () => {
  stopBLEScan();
  uni.navigateBack({
    delta: 1
  });
};

// 添加菜单并返回上级
const AddMyMenuByUser = (param) => {
  if (param) {
    try {
      stopBLEScan();
      const pages = getCurrentPages(); // 获取所有页面栈实例列表
      const prevPage = pages[pages.length - 2]; // 上一页页面实例
      prevPage.$vm.$.exposed.SelectionChanged({
        type: type.value || 'printer',
        ...param
      });
      uni.navigateBack({
        delta: 1
      });
    } catch (e) {
      // 处理异常
      console.error(e);
    }
  }
};

// 下拉刷新
const templateUpper = () => {
  if (!triggered.value) {
    triggered.value = true;
    devices.value = [];
    openBluetoothAdapterAndCheckState();
    setTimeout(() => {
      triggered.value = false;
    }, 2000);
  }
};

</script>
<style lang="scss" scoped>
::v-deep uni-page-body {
  height: 100%;
}
.content {
  display: flex;
  height: 100%;
  flex-direction: column;
  background-color: #F2F2F2;
  padding: 0px !important;
  justify-content: space-between;
}
.footer {
  display: flex;
  flex: 1 1 auto;
  overflow: hidden;
}
.content-img {
  background-color: #FFFFFF;
  background-size: 100% 420rpx;
  background-repeat: no-repeat;
  width: 100%;
}

.navigation {
  flex: 0 0 auto;
  margin-bottom: 5px;
}
.uni-list {
  background-color: #fff;
  position: relative;
  width: 100%;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: vertical;
  -webkit-box-direction: normal;
  -webkit-flex-direction: column;
  flex-direction: column;
}

uni-radio-group,
uni-checkbox-group {
  width: 100%;
}

uni-radio-group {
  display: block;
}

.uni-list-cell {
  position: relative;
  display: -webkit-box;
  display: -webkit-flex;
  display: flex;
  -webkit-box-orient: horizontal;
  -webkit-box-direction: normal;
  -webkit-flex-direction: row;
  flex-direction: row;
  -webkit-box-pack: justify;
  -webkit-justify-content: space-between;
  justify-content: space-between;
  -webkit-box-align: center;
  -webkit-align-items: center;
  align-items: center;
  -webkit-box-pack: start;
  -webkit-justify-content: flex-start;
  justify-content: flex-start;
}

.uni-list-cell-pd {
  padding: 10rpx;
}

.uni-list-cell::after {
  position: absolute;
  z-index: 3;
  right: 0;
  bottom: 0;
  left: 0px;
  height: 1px;
  content: "";
  -webkit-transform: scaleY(.5);
  transform: scaleY(.5);
  background-color: #c8c7cc;
}

.uni-list-cell:last-child::after {
  height: 0px;
}

.uni-list:after {
  position: absolute;
  z-index: 10;
  right: 0;
  bottom: 0;
  left: 0;
  height: 1px;
  content: "";
  -webkit-transform: scaleY(.5);
  transform: scaleY(.5);
  background-color: #c8c7cc;
}

.menu-footer {
  display: flex;
  flex-direction: row;
  padding: 15rpx;
  gap: 5rpx;
}
.flex_2 {
  font-size: 0.8rem;
  color: #9a9a9a;
}


</style>
